package org.je.util;

/**
 * @author fanyifeng 2012-8-31 上午11:13:15
 */
public class ByteUtil
{
	/**
	 * @param bArrs
	 * @return combined byte[]
	 */
	public static byte[] combine(byte[]... bArrs) {
		int totalLength = 0;
		for (byte[] arr : bArrs) {
			totalLength += arr.length;
		}
		byte[] dest = new byte[totalLength];
		int off = 0;
		for (byte[] arr : bArrs) {
			System.arraycopy(arr ,0 ,dest ,off ,arr.length);
			off += arr.length;
		}
		return dest;
	}

	/**
	 * @param src
	 * @param dest
	 * @return index or -1
	 */
	public static int indexOf(byte[] src, byte[] dest) {
		return indexOf(src ,dest ,0);
	}

	/**
	 * @param src
	 * @param dest
	 * @param off
	 * @return index or -1
	 */
	public static int indexOf(byte[] src, byte[] dest, int off) {
		if (src == null || dest == null)
			throw new NullPointerException("src:" + src + ",dest:" + dest);
		if (off < 0 || off > src.length)
			throw new IndexOutOfBoundsException("off:" + off + ",src.length:" + src.length);

		if (dest.length == 0 || off + dest.length > src.length)
			return -1;

		int matchEndIndex = src.length - dest.length;
		for (int i = off; i <= matchEndIndex; ++i) {
			if (match_not_check(src ,dest ,i))
				return i;
		}
		return -1;
	}

	/**
	 * 外围调用，需要添加这行代码才能正确使用 <br/>
	 * if (dest.length == 0) return false;
	 */
	static boolean match_not_check(byte[] src, byte[] dest, int off) {
		for (int i = 0; i < dest.length; ++i) {
			if (src[off + i] != dest[i])
				return false;
		}
		return true;
	}

	/**
	 * @param src
	 * @param start
	 * @param end
	 * @return subBytes
	 */
	public static byte[] subBytes(byte[] src, int start, int end) {
		byte[] dest = new byte[end - start];
		System.arraycopy(src ,start ,dest ,0 ,end - start);
		return dest;
	}
}
